package com.kygeng.namenode;

import com.kygeng.namenode.rpc.service.NameNodeServiceGrpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;

/**
 * @Title: NameNodeRpcServer
 * @Author: kygeng
 * @Package: com.kygeng.namenode
 * @Date: 2025/3/2 18:16
 * @Description: NameNode的rpc服务的接口
 */
public class NameNodeRpcServer {


    private static final int DEFAULT_PORT = 50070;

    private Server server = null;

    /**
     * 负责管理元数据的核心组件
     */
    private FSNamesystem namesystem;
    /**
     * 负责管理集群中所有的datanode的组件
     */
    private DataNodeManager datanodeManager;

    public NameNodeRpcServer(
            FSNamesystem namesystem,
            DataNodeManager datanodeManager) {
        this.namesystem = namesystem;
        this.datanodeManager = datanodeManager;
    }

    public void start() throws Exception {
        //启动一个rpc server
        server = ServerBuilder.forPort(DEFAULT_PORT)
                .addService(NameNodeServiceGrpc.bindService(new NameNodeServiceImpl(namesystem, datanodeManager)))
                .build()
                .start();

        System.out.println("NameNodeRpcServer启动了,监听端口号：" + DEFAULT_PORT);

        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                System.out.println("NameNodeRpcServer收到关闭的信号,开始关闭");
                NameNodeRpcServer.this.stop();
                System.out.println("NameNodeRpcServer已经关闭");
            }
        });
    }

    public void stop() {
        if(server != null) {
            server.shutdown();
        }
    }

    public void blockUntilShutdown() throws Exception {
        if(server!= null) {
            server.awaitTermination();
        }
    }
}
